package com.xiaoyu.net.secret;

import android.util.Base64;


import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

/***
 * rsa 加密模块相关业务处理
 */
public class RSAUtil {

    private final static int KEY_SIZE = 1024;
    private static final String RSA = "RSA";
    private static final String TRANSFORMATION = "RSA/ECB/PKCS1Padding";

    /***
     * 公钥加密
     * @param source 加密源文字
     * @param publicKey 公钥
     * @return encrypt params
     */
    public static String encryptPublic(String source, String publicKey) throws Exception {
        byte[] decoded = Base64.decode(publicKey, Base64.DEFAULT);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance(RSA).generatePublic(new X509EncodedKeySpec(decoded));
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        byte[] encoded = cipher.doFinal(source.getBytes(StandardCharsets.UTF_8));
        return Base64.encodeToString(encoded, Base64.DEFAULT);
    }
}
